from django.db import models
from django.utils import timezone
from personnel.models import Equipment


class ExperimentPlan(models.Model):
    """试验计划模型"""
    EXPERIMENT_TYPE_CHOICES = [
        ('单机', '单机'),
        ('整星', '整星'),
        ('自建', '自建'),
    ]
    
    SOURCE_CHOICES = [
        ('scheduling_system', '总装调度管理系统'),
        ('dingtalk', '钉钉预约'),
        ('manual', '手动录入'),
    ]
    
    # 基本信息
    experiment_type = models.CharField(max_length=20, choices=EXPERIMENT_TYPE_CHOICES, verbose_name='试验类型')
    equipment = models.ForeignKey(Equipment, on_delete=models.CASCADE, verbose_name='使用设备')
    
    # 钉钉同步字段
    project = models.CharField(max_length=300, blank=True, null=True, verbose_name='项目名称')
    experiment_report_name = models.CharField(max_length=500, blank=True, null=True, verbose_name='试验项目（报告）名称')
    depart = models.CharField(max_length=200, blank=True, null=True, verbose_name='部门')
    days = models.CharField(max_length=10, blank=True, null=True, verbose_name='试验天数')
    bid = models.CharField(max_length=100, blank=True, null=True, verbose_name='钉钉业务ID')
    addr = models.CharField(max_length=100, blank=True, null=True, verbose_name='试验地址')
    details = models.TextField(blank=True, null=True, verbose_name='详细信息JSON')
    
    # 时间安排
    enter_date = models.DateField(verbose_name='入场时间')
    start_date = models.DateField(verbose_name='开始时间')
    complete_date = models.DateField(verbose_name='完成时间')
    end_date = models.DateField(verbose_name='出场时间')
    
    # 状态信息
    source = models.CharField(max_length=30, choices=SOURCE_CHOICES, default='manual', verbose_name='数据来源')
    
    # 是否可调整
    is_adjustable = models.BooleanField(default=True, verbose_name='是否可调整')
    
    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'experiment_plan'
        verbose_name = '试验计划'
        verbose_name_plural = '试验计划管理'
        ordering = ['enter_date', 'start_date']
        unique_together = ['equipment', 'enter_date', 'end_date', 'experiment_type', 'is_adjustable']
    
    def __str__(self):
        return f"{self.project} - {self.equipment.name} ({'可调整' if self.is_adjustable else '不可调整'})"
    
    def clean(self):
        """验证时间逻辑"""
        from django.core.exceptions import ValidationError
        
        if self.enter_date > self.start_date:
            raise ValidationError('开始时间不能早于入场时间')
        
        if self.start_date > self.complete_date:
            raise ValidationError('完成时间不能早于开始时间')
        
        if self.complete_date > self.end_date:
            raise ValidationError('出场时间不能早于完成时间')
    
    def save(self, *args, **kwargs):
        self.clean()
        super().save(*args, **kwargs)


class ExperimentDocument(models.Model):
    """试验计划文档模型 - 存储钉钉数据的文档"""
    experiment_plan = models.ForeignKey(
        ExperimentPlan, 
        on_delete=models.CASCADE, 
        related_name='documents',
        verbose_name='关联试验计划'
    )
    
    # 文档基本信息
    file_name = models.CharField(max_length=255, verbose_name='文件名')
    file_size = models.BigIntegerField(verbose_name='文件大小(字节)')
    file_type = models.CharField(max_length=50, verbose_name='文件类型')
    
    # 钉钉相关信息
    dingtalk_file_id = models.CharField(max_length=100, blank=True, null=True, verbose_name='钉钉文件ID')
    upload_source = models.CharField(
        max_length=20, 
        choices=[('dingtalk', '钉钉上传'), ('manual', '手动上传')],
        default='dingtalk',
        verbose_name='上传来源'
    )
    

    
    # 时间戳
    uploaded_at = models.DateTimeField(auto_now_add=True, verbose_name='上传时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'experiment_document'
        verbose_name = '试验文档'
        verbose_name_plural = '试验文档管理'
        ordering = ['-uploaded_at']
    
    def __str__(self):
        return f"{self.experiment_plan.project} - {self.file_name}"
    
    @property
    def file_size_mb(self):
        """返回文件大小(MB)"""
        return round(self.file_size / (1024 * 1024), 2)
    
    def get_file_extension(self):
        """获取文件扩展名"""
        return self.original_name.split('.')[-1].lower() if '.' in self.original_name else ''
